package com.atguigu.java;

import org.junit.Test;

import java.util.*;

/**
 * @author : leimingchao
 * @date Date : 2021年10月06日 22:29
 */
public class TreeMapTest {

    /**
     * 向TreeMap中添加key-value，要求key必须是由同一个类创建的对象
     * 因为要按照key进行排序：自然排序、定制排序
     */
    /**
     * 自然排序
     */
    @Test
    public void test1() {
        TreeMap map = new TreeMap();
        User user1 = new User("Tom",12);
        User user2 = new User("Jerry",32);
        User user3 = new User("Jack",20);
        User user4 = new User("Rose",18);

        map.put(user1,98);
        map.put(user2,89);
        map.put(user3,76);
        map.put(user4,100);

        Set set = map.entrySet();
        Iterator iterator = set.iterator();

        while (iterator.hasNext()) {
            Object object = iterator.next();
            //entrySet集合中的元素都是Entry
            Map.Entry entry = (Map.Entry) object;

            System.out.println(entry.getKey() + "------>" + entry.getValue());
        }
    }

    /**
     * 定制排序
     */
    @Test
    public void test2() {
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {

                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(),u2.getAge());
                }
                throw new RuntimeException("输入的类型不匹配");
            }
        });
        User user1 = new User("Tom",12);
        User user2 = new User("Jerry",32);
        User user3 = new User("Jack",20);
        User user4 = new User("Rose",18);

        map.put(user1,98);
        map.put(user2,89);
        map.put(user3,76);
        map.put(user4,100);
        Set set = map.entrySet();
        Iterator iterator = set.iterator();

        while (iterator.hasNext()) {
            Object object = iterator.next();
            //entrySet集合中的元素都是Entry
            Map.Entry entry = (Map.Entry) object;

            System.out.println(entry.getKey() + "------>" + entry.getValue());
        }
    }
}
